<!--
 * @Date: 2023-02-12 16:46:11
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-21 14:29:31
 * @FilePath: \A19\frontend\src\components\TestDemo.vue
-->
<!--
 * @Date: 2023-02-12 16:46:11
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-02-17 02:05:09
 * @FilePath: \A19\frontend\src\components\TestDemo.vue
-->
<template>
    <div id="createTest" class="container">
      <div class="wrapper">
        <div class="left">
          <div class="header">
            {{ testInfo?.name }}
          </div>
  
          <div v-for="kv,index in catedQuestions" :key="kv[0]">
            <div class="cate" v-show="kv[1].length !== 0">
              {{ kv[0] }} 
            </div>
            <div 
              class="quest" 
              @click="enter(question)" 
              v-for="(question,index) in kv[1]" 
              :key="question._id"
              :style="{backgroundColor:culBackcolor(question._id)}"
            >
              {{ index + 1 }}
              <span v-show="done.find(d => d===question._id)" style="float: right;"><el-icon><Check /></el-icon></span>
            </div>
          </div>
        </div>
        <div class="right">
          <div class="controllers">
            <ElButton type="primary" plain @click="endTest">{{ examOrHomework === 'exam'?'结束考试':'提交' }}</ElButton>
          </div>
          <div class="form">
            <div v-if="currentQues">
              <div class="item">
                <div class="hint">
                  题目:
                </div>
                {{ currentQues?.question.question }}
                <span style="float: right;"><span class="hint">分数：</span>{{ currentQues?.question.score }}</span>
              </div>

              <div class="item" v-if="currentQues?.question.selections">
                <div class="hint">
                  选项:
                </div>
                <div class="selection">
                  <el-checkbox-group v-model="answers.find(a => a.questionId === currentQues?._id)!.selections">
                    <el-checkbox :key="sel" v-for="sel in currentQues?.question.selections" :label="sel" name="type" />
                  </el-checkbox-group>
                </div>
              </div>
              <div class="item" v-else-if="currentQues?.question.questionCount">
                <div class="hint">
                  填空:
                </div>
                <div class="input"  v-for="(answer,index) in answers.find(a => a.questionId === currentQues?._id)!.answers">
                  <el-input v-model="answer.answer"/>
                </div>
              </div>
              <div class="item" v-else>
                <div class="hint">
                  答案:
                </div>
                <div class="input">
                  <el-input type="textarea" :autosize="{ minRows: 6, maxRows: 8 }" v-model="answers.find(a => a.questionId === currentQues?._id)!.answer"/>
                </div>
              </div>
            </div>
            <div v-else>
                        <div style="height: 200px;line-height: 200px;">点击题目作答</div>
                    </div>
          </div>
        </div>
      </div>
  </div>
</template>

<script lang="ts" setup>
import { useClientStore } from "@/pinia/stores/client";
import { storeToRefs } from "pinia";
import { Ref, onMounted, onUnmounted, ref, watch, defineProps, computed, reactive } from 'vue';
import { tests } from "@/shared/types/tests";
import { testhooks } from '../hooks/test/testhooks';
import { questions } from "@/shared/types/Question";
import { Router, useRoute, useRouter } from 'vue-router';
import { ApiReturn } from "tsrpc-browser";
import { ResCreateUserHomework } from "@/shared/protocols/Create/PtlCreateUserHomework";
// import { studentAnswer, answer } from '../shared/types/Answer';
let loadingInstance:any
// //hooks
// // RTChook()
// // const videoRef = ref<HTMLVideoElement>()
const route = useRoute()
const router = useRouter()
const examOrHomework = ref<'exam' | 'homework'>((route.name as 'testDemo' | 'homeworkDemo') === 'testDemo'?'exam':'homework')
// const props = defineProps<{ testId:string }>();
const testId = route.params.testId as string
const testInfo = ref<{
    _id: string,
    course: string,
    startTime: Date,
    endTime: Date,
    name: string,
    status: "saved" | "published"
    questions:Array<questions>
   }>()
const catedQuestions = computed(() =>{
  const qus = new Map<string,Array<questions>>()
  qus.set('选择题',new Array<questions>())
  qus.set('填空题',new Array<questions>())
  qus.set('简答题',new Array<questions>())
  qus.set('判断题',new Array<questions>())
    testInfo.value?.questions.forEach(question =>{
    qus.get(question.question.type)?.push(question)
  })

  return qus
})
const { currentUser,client,currentCourseId } = storeToRefs(useClientStore())

if(examOrHomework.value === 'exam'){
  const {wsClient} = testhooks(testId)
  wsClient.listenMsg('AMessages/Test/Warn',async msg =>{
    if(msg.type === 'warn'){
      ElMessage.warning(`教师提醒：${msg.msg}`)
    }
    else{
      ElMessage.error(`被强制收卷`)
      const ret = await client.value.callApi('Create/CreateUserHomework',{
        examOrHomework:examOrHomework.value,
        test:testId,
        submitTime:new Date(),
        score:0,
        answers:answers.value.map(answer =>{
          return {
            ...answer,
            answers:answer.answers?.map(a => a.answer)
          }
        })
      })
      if(ret.isSucc){
        // ElMessage.success('提交成功')
        router.back()
      }
    }
  })
}

const answers = ref(new Array<{
  questionId:string
  answer?:string,//简答题
  selections?:Array<string>,//选择题
  answers?: Array<{
    answer:string
  }>//填空题
  getPoint:number
}>())

const currentQues = ref<questions>()
const enter = (question:questions)=>{
  currentQues.value = question
  console.log(question);
}
const done = computed(()=>{
  const ans = answers.value.filter(answer =>{
    if(answer.answer){
      console.log('answer');
      
      return true
    }
    if(answer.answers && !answer.answers.find(a => a.answer === '')){
      return true
    }
    if(answer.selections && answer.selections.length !== 0){
      console.log('selections');
      return true
    }
    else{
      return false
    }
  })
  return ans.map(a => a.questionId)
})
const culBackcolor = (id:string)=>{
  if( currentQues.value?._id === id){
    return '#fde2e247'
  }
  
}
// const getinput = (index:number)=>{
//   console.log(index);
//   // const input = answers.value.find(a => a.questionId === currentQues.value!._id)!.answers
//   // if(answers.value.find(a => a.questionId === currentQues.value!._id)!.answers)
//   return text
// }
const endTest = async ()=>{
  try {
    if(done.value.length !== answers.value.length){
      await ElMessageBox.confirm('你还有没回答的问题，确定提交吗？')
    }
    else{
      await ElMessageBox.confirm('确定提交吗？')
    }
    const ret = await client.value.callApi('Create/CreateUserHomework',{
      examOrHomework:examOrHomework.value,
      test:testId,
      submitTime:new Date(),
      score:0,
      answers:answers.value.map(answer =>{
        return {
          ...answer,
          answers:answer.answers?.map(a => a.answer)
        }
      })
    })
    if(ret.isSucc){
      ElMessage.success('提交成功')
      router.back()
    }
  } catch (error) {
    console.log(error);
  }
}
const forceEndTest = async () =>{
  return client.value.callApi('Create/CreateUserHomework',{
    examOrHomework:examOrHomework.value,
    test:testId,
    submitTime:new Date(),
    score:0,
    answers:answers.value.map(answer =>{
      return {
        ...answer,
        answers:answer.answers?.map(a => a.answer)
      }
    })
  })
}

let timerInterval:NodeJS.Timer
const timer = (endTime:Date,endTest:Function,router:Router) =>{
  let interval = setInterval(async () =>{
    if(new Date > endTime){
      //强制交卷
      clearInterval(interval)
      const ret = await endTest()
      ElMessage.error('已强制提交')
      router.back()
    }
  },1000)
  return interval
}

onMounted(async () =>{
    loadingInstance = ElLoading.service({
        target:'#createTest',
    })

    if(!testId){
      loadingInstance.close()
      ElMessage.error('不存在')
      router.back()
      return
    }

    const ret = await client.value.callApi('Get/GetTestQuestions',{
        test:testId,
        examOrHomework:examOrHomework.value
    })
    if(ret.isSucc){
        testInfo.value = ret.res.test[0]
        timerInterval = timer(testInfo.value.endTime,forceEndTest,router)
        currentCourseId.value = testInfo.value.course
        // answers.value = new Array<studentAnswer>(ret.res.test[0].questions.length)
        ret.res.test[0].questions.forEach(question =>{
          const answerss = new Array<{answer:string}>()
          for (let index = 0; index < (question.question.questionCount || 0); index++) {
            answerss.push({
              answer:''
            })
          }
          answers.value.push({
            questionId:question._id,
            getPoint:0,
            answer:question.question.type === '简答题'?'':undefined,
            answers:answerss.length === 0?undefined:answerss,
            selections:(question.question.type === '选择题' || question.question.type === '判断题')?new Array<string>():undefined
          })
        })
    }
    loadingInstance.close()

    // const ret1 = await client.value.callApi('Get/GetQuestions',{})
    // if(ret1.isSucc){
    //   console.log(ret1.res);
    // }
})

onUnmounted(()=>{
  clearInterval(timerInterval)
})
</script>

<style lang="less" scoped>
@fontColor: #a6a6a6;
*{
  user-select: none;
}
.container {
  height: 100%;
  width: 100%;
  background-color: #f2f4f7;
  padding: 5vh 0;
  overflow: auto;
  .wrapper {
    width: 80%;
    height: 90%;
    // background-color: aliceblue;
    position: relative;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;

    .left {
      width: 25%;
      height: 100%;
      background-color: white;
      border-radius: 10px;
      display: flex;
      flex-direction: column;
      overflow: auto;
      padding-top: 50px;
      &>div>div{
        .de-btn{
          float: right;
          font-size: 16px;
          display:none;
          line-height: 30px;
          color:#a6a6a6;
        }
      }
      &>div>div:hover{
        background-color: aliceblue;
        .de-btn{
          display: inline;
        }
      }
      .header{
        border-radius: 10px;
        height: 50px;
        color: #000;
        font-size: 20px;
        text-align: left;
        line-height: 65px;
        padding: 0 20px;
        user-select: none;
        position: absolute;
        top: 0;
        left: 0;
        background: white;
      }
      .cate{
        height: 30px;
        color: black;
        font-size: 12px;
        font-weight: bold;
        line-height: 30px;
        padding: 0 20px;
        background: white!important;
        // cursor: pointer;
      }
      .quest{
        height: 30px;
        color:@fontColor;
        font-size: 13px;
        line-height: 30px;
        padding: 0 20px;
        cursor: pointer;
      }
    }
    .right {
      width: 72%;
      height: 100%;
      // background-color: white;
      & > div {
        border-radius: 10px;
      }
      .controllers {
        height: 12%;
        width: 100%;
        background-color: white;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding: 0 30px;
        .text {
          color: @fontColor;
        }
        .el-button {
          margin-left: 20px;
        }
      }
      .form {
        position: relative;
        margin-top: 4%;
        // height: 80%;
        width: 100%;
        background-color: white;
        text-align: center;
        // line-height: 500px;
        color: @fontColor;
        padding: 40px;
        .hint{
            color: @fontColor;
            font-size: 14px;
        }
        .item{
          // height: 40px;
          text-align: left;
          color: black;
          line-height: 40px;
          margin: 10px 0;
          .input{
            // padding: 0 20px;
            padding-left: 0%;
            width: 60%;
            margin-bottom: 10px;
          }
          .selection{
            // padding-left: 20px;
            height: 40px;
          }
        }
        .foot{
          padding-top:10px;
        }
      }
    }
  }
}
</style>
